package clock.socoolby.com.clock.event.livedata;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.lifecycle.LiveData;

public class SystemActionLiveData extends LiveData<String> {
    private Context mContext;
    private IntentFilter intentFilter;

    /** 广播监听器 */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null || action.isEmpty()) {
                return;
            }
            setValue(action);
        }
    };

    /**
     * 构造函数
     *
     * @param context {@link Context}
     * @param actions 需要监听的Action {@link Intent#ACTION_XXX}
     */
    public SystemActionLiveData(Context context, String... actions) {
        mContext = context;
        intentFilter = new IntentFilter();
        for (String action : actions) {
            intentFilter.addAction(action);
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
        if (mContext != null) {
            mContext.registerReceiver(mReceiver, intentFilter);
        }
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        if (mContext != null) {
            mContext.unregisterReceiver(mReceiver);
        }
    }
}